<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <meta name="referrer" content="no-referrer" />
    <title>在线聊天</title>

    <!--图标库-->
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css'>

    <!-- 默认样式-->
    <link rel="stylesheet" href="<?php echo base_url(); ?>public/chat/css/reset.min.css">

    <!-- 主要样式-->
    <link rel="stylesheet" href="<?php echo base_url(); ?>public/chat/css/style.css">

    <script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
    <script src="<?php echo base_url(); ?>public/layui/layui.js" charset="utf-8"></script>

    <script type="text/javascript" src="<?php echo base_url(); ?>public/jquery.min.js"></script>
    <script type="text/javascript" src='<?php echo base_url(); ?>public/chat/js/handlebars.min.js'></script>
    <script type="text/javascript" src='<?php echo base_url(); ?>public/chat/js/list.min.js'></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>public/chat/js/script.js"></script>

    <!-- 表情相关-->
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>public/face/public/style/cssreset-min.css">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>public/face/public/style/common.css">
    <script type="text/javascript" src="<?php echo base_url(); ?>public/face/code/jquery.emoticons.js"></script>
    <!-- 表情相关-->

</head>

<style>
    .layui-layer layui-layer-dialog{
        width: 280px;
    }
</style>

<body>

<div class="container clearfix">
    <div class="people-list" id="people-list">
        <div class="search">
            <input type="button" onclick="avatarUpload()" value="头像投稿" />

        </div>
        <ul class="list" id="leftList">

            <a href="javascript:;" style="color: white" onclick="goChat(0)">
                <li class="clearfix">
                    <img src="<?php echo base_url().'/public/home.png'; ?>" alt="avatar" />
                    <div class="about">
                        <div class="name">大厅</div>
                        <div class="status">
                            <i class="fa fa-circle online" style="float: left;margin-top: 6px;"></i><span id="newMsg_0"></span>
                        </div>
                    </div>
                </li>
            </a>

            <?php if(!empty($list)){ foreach ($list as $val){ ?>
                <a href="javascript:;" id="left_<?php echo $val['id'];?>" style="color: white" onclick="goChat(<?php echo $val['id'];?>,'<?php echo $val['nick_name'];?>','<?php echo $val['url'];?>')">
                <li class="clearfix">
                    <img src="<?php echo $val['url']; ?>" alt="avatar" />
                    <div class="about">
                        <div class="name"><?php echo $val['nick_name'];?></div>
                        <div class="status">
                            <i class="fa fa-circle online" style="float: left;margin-top: 6px;"></i><span id="newMsg_<?php echo $val['id']?>"></span>
                        </div>
                    </div>
                </li>
                </a>
            <?php }} ?>

        </ul>
    </div>

    <div class="chat">
        <div class="chat-header clearfix">
            <img id="to_avatar" src="<?php echo base_url().'/public/home.png'; ?>" alt="avatar" />

            <div class="chat-about">
                <div class="chat-with" id="to_name">大厅</div>
                <div class="chat-num-messages" id="hone_desc">展示近7天聊天记录</div>
            </div>
            <img style="float: right" id="homeMyHead" src="" alt="">
        </div> <!-- end chat-header -->

        <div class="chat-history" id="chat-history">
            <ul id="chat_box">

            </ul>

        </div> <!-- end chat-history -->

        <div class="chat-message clearfix">
            <textarea name="message-to-send" id="message-to-send" placeholder ="请输入内容" rows="3"></textarea>

<!--            <i style="font-size: 20px;" class="fa fa-file-image-o"></i>&nbsp;-->
<!--            <button style="float: left"></button>-->

<!--            <span class="emoticons">-->
<!--            <span class="trigger"><i style="font-size: 22px;margin-left: 12px;" class="fa fa-smile-o"></i></span>-->
<!--            </span>-->
<!--            <button  style="float: left;color: #86BB71;margin-top: 0px;"></button>-->

            <button id="sendMsg" onclick="sendMsg()">发送</button>

        </div> <!-- end chat-message -->

    </div> <!-- end chat -->

</div> <!-- end container -->

<!--<div class="emoticons">-->
<!--    <div class="publisher">-->
<!--        <p><textarea name="content"></textarea></p>-->
<!--        <p><a class="trigger" href="javascript:;">☺</a></p>-->
<!--    </div>-->
<!--    <div style="text-align:right;"><button id="format">解析</button></div>-->
<!--    <div id="result" class="result"></div>-->
<!--</div>-->

<input type="hidden" id="user_id">
<input type="hidden" id="client_id">
<input type="hidden" id="to_uid" value="0">
<input type="hidden" id="page" value="0">

</body>
<script>
    layui.use('layer',function () {

        /**
         * 与GatewayWorker建立websocket连接，域名和端口改为你实际的域名端口，
         * 其中端口为Gateway端口，即start_gateway.php指定的端口。
         * start_gateway.php 中需要指定websocket协议，像这样
         * $gateway = new Gateway(websocket://0.0.0.0:8282);
         */

        ws = new WebSocket("ws://127.0.0.1:8282");

        // 服务端主动推送消息时会触发这里的onmessage
        ws.onmessage = function(e){
            // json数据转换成js对象
            var data = eval("("+e.data+")");
            var type = data.type || '';

            console.log(data);

            switch(type){
                // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
                case 'init':
                    layer.msg(data.msg);

                    // 利用jquery发起ajax请求，将client_id发给后端进行用户生成并与用户id绑定
                    var request_url = "<?php echo base_url(); ?>"+'index/bindUser';

                    if (data.isAlert)
                    {
                        //设置昵称
                        layer.open({
                            title:"你的昵称",
                            content: ' <input style="width: 215px;height: 33px;" type="text" id="nick_val" class="layui-input">',//内容区域
                            btn: ['确认'],
                            btn1: function(index){
                                //按钮【按钮一】的回调
                                var val = $("#nick_val").val();

                                if (!val)
                                {
                                    alert('昵称不能为空');
                                } else {
                                    $.ajax({
                                        type: "POST",
                                        dataType: "json",
                                        url: request_url,
                                        data: {
                                            client_id: data.client_id,
                                            nick:val,
                                            real_ip:data.real_ip
                                        },
                                        success: function (result) {
                                            if (result.code != 200)
                                            {
                                                layer.msg(result.msg);
                                                return;
                                            }

                                            //设置头像和昵称
                                            $("#myAvatar").attr('src',result.data.avatar);

                                            //设置当前用户id
                                            $("#user_id").val(result.data.user_id);
                                            $("#client_id").val(data.client_id);

                                            //我的头像
                                            $("#homeMyHead").attr('src',result.data.avatar);

                                            //聊天记录
                                            getChatLog(result.data.list,result.data.user_id);
                                        },
                                        error : function() {
                                            layer.msg('服务器连接失败');
                                        }
                                    });

                                    layer.close(index);//关闭弹框
                                }
                            },
                            // 右上角关闭按钮的点击事件
                            cancel: function(){
                                $.ajax({
                                    type: "POST",
                                    dataType: "json",
                                    url: request_url,
                                    data: {
                                        client_id: data.client_id,
                                        nick:'',
                                        real_ip:data.real_ip
                                    },
                                    success: function (result) {
                                        if (result.code != 200)
                                        {
                                            layer.msg(result.msg);
                                            return;
                                        }

                                        //设置头像和昵称
                                        $("#myAvatar").attr('src',result.data.avatar);

                                        //设置当前用户id
                                        $("#user_id").val(result.data.user_id);
                                        $("#client_id").val(data.client_id);

                                        //我的头像
                                        $("#homeMyHead").attr('src',result.data.avatar);

                                        //聊天记录
                                        getChatLog(result.data.list,result.data.user_id);
                                    },
                                    error : function() {
                                        layer.msg('服务器连接失败');
                                    }
                                });
                            }
                        });
                    } else {
                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            url: request_url,
                            data: {
                                client_id: data.client_id,
                                real_ip:data.real_ip
                            },
                            success: function (result) {
                                if (result.code != 200)
                                {
                                    layer.msg(result.msg);
                                    return;
                                }

                                //设置头像和昵称
                                $("#myAvatar").attr('src',result.data.avatar);

                                //设置当前用户id
                                $("#user_id").val(result.data.user_id);
                                $("#client_id").val(data.client_id);

                                //我的头像
                                $("#homeMyHead").attr('src',result.data.avatar);

                                //聊天记录
                                getChatLog(result.data.list,result.data.user_id);
                            },
                            error : function() {
                                layer.msg('服务器连接失败');
                            }
                        });
                    }

                    break;
                case 'text':
                    //新消息-先判断是大厅消息还是私人消息
                    var to_uid = $("#to_uid").val(); //当前对话是大厅还是私人

                    if (parseInt(to_uid) == parseInt(data.to_uid))
                    {
                        //正在聊天
                        var log = '<li>' +
                            '<div class="message-data"><span class="message-data-name"><img style="width: 40px;margin-bottom: -13px;" src="'+data.avatar+'" alt="avatar" />'+data.nick+'</span> <span class="message-data-time" >'+data.time+'</span></div>' +
                            '<div class="message my-message">'+data.msg+'</div>'+
                            '</li>';

                        $("#chat_box").append(log);

                        //滚动条定位至最下方
                        $("#chat-history").scrollTop($("#chat-history")[0].scrollHeight);
                    } else {
                        var msg = data.msg;

                        var m   = msg.substr(0,10);

                        if (parseInt(data.to_uid) == parseInt("0"))
                        {
                            //私人消息
                            $("#newMsg_0").text(m);
                        } else {
                            //私人消息
                            $("#newMsg_"+data.from_uid).text(m);
                        }

                    }
                    break;
                case 'connect':
                    //有新用户连接--只添加一次
                    if(!document.getElementById('left_'+data.id)){
                        var newCon = '<a href="javascript:;" id="left_'+data.id+'" style="color: white" onclick="goChat('+data.id+', '+"'"+data.nick+"'"+','+"'"+data.avatar+"'"+')">' +
                            '<li class="clearfix"><img src="'+data.avatar+'" alt="avatar"><div class="about">'+
                            '<div class="name">'+data.nick+'</div><div class="status"><i class="fa fa-circle online" style="float: left;margin-top: 6px;"></i>'+
                            '</div></div></li>'+
                            '</a>';

                        $("#leftList").append(newCon);
                    }
                    break;
                case 'close':
                    //有用户断开连接
                    $("#left_"+data.id).remove();
                    break;
                default :
                //alert(e.data);
            }
        };

    });

    //发送聊天内容
    function sendMsg()
    {
        $("#sendBut").attr('disabled',true);

        var content = $("#message-to-send").val();

        if (!content)
        {
            $("#sendBut").attr('disabled',false);
            layer.msg('不能发送空白消息');
            return;
        }

        var user_id     = $("#user_id").val();
        var to_uid      = $("#to_uid").val();
        var client_id   = $("#client_id").val();
        var request_url = "<?php echo base_url(); ?>"+'index/chatRecord';

        if (!user_id)
        {
            $("#sendBut").attr('disabled',false);
            layer.msg('请刷新后重试');
            return;
        }

        $.ajax({
            type: "POST",
            dataType: "json",
            url: request_url,
            data: {
                content: content,
                user_id: user_id,
                to_uid : to_uid,
                client_id:client_id,
            },
            success: function (result) {
                $("#sendBut").attr('disabled',false);

                layer.msg(result.msg);

                if (result.code != 200)
                {
                    return false;
                }

                //内容渲染
                var newMsg = '<li class="clearfix">' +
                    '<div class="message-data align-right"><span class="message-data-time" >'+result.data.time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+result.data.nick+'</span> <img style="width: 40px;margin-bottom: -13px;" src="'+result.data.avatar+'" alt="avatar" /></div>' +
                    '<div class="message other-message float-right">'+result.data.content+'</div>'+
                    '</li>';

                $("#chat_box").append(newMsg);

                $("#message-to-send").val('');

                var div = document.getElementById('chat-history');
                div.scrollTop = div.scrollHeight;
            },
            error : function() {
                $("#sendBut").attr('disabled',false);
                layer.msg('服务器连接失败');
            }
        });
    }

    //渲染聊天记录
    function getChatLog(list,now_uid)
    {
        let arrNew = new Array();

        for (var i = list.length - 1; i >= 0; i--) {

            var log = '';
            if (list[i].uid == now_uid)
            {
                log = '<li class="clearfix">' +
                    '<div class="message-data align-right"><span class="message-data-time" >'+list[i].create_time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+list[i].nick_name+'</span> <img style="width: 40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" /></div>' +
                    '<div class="message other-message float-right">'+list[i].content+'</div>'+
                    '</li>';
            } else {
                log = '<li>' +
                    '<div class="message-data"><span class="message-data-name"><img style="width: 40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" />'+list[i].nick_name+'</span> <span class="message-data-time" >'+list[i].create_time+'</span></div>' +
                    '<div class="message my-message">'+list[i].content+'</div>'+
                    '</li>';
            }

            arrNew.push(log);
        }

        $("#chat_box").html(arrNew);

        //滚动条定位至最下方
        $("#chat-history").scrollTop($("#chat-history")[0].scrollHeight);
    }

    //点击在线用户获取聊天记录
    function goChat(to_uid,nick='',avatar='')
    {
        $("#to_uid").val(to_uid); //赋值当前聊天对象

        var user_id     = $("#user_id").val();

        var request_url = "<?php echo base_url(); ?>"+'index/getPageChatRecord';

        if (nick && avatar)
        {
            $("#hone_desc").hide();
            $("#to_name").text(nick);
            $("#to_avatar").attr('src',avatar);
            $("#to_name").css("margin-top","12px");
        } else {
            //回到大厅
            $("#hone_desc").show();
            $("#to_name").text('大厅');
            $("#to_name").css("margin-top","0px");
            $("#to_avatar").attr('src',"<?php echo base_url().'/public/home.png'; ?>");
        }

        if (page != '')
        {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: request_url,
                data: {
                    to_uid: to_uid,
                    user_id: user_id,
                    page:0,
                },
                success: function (result) {

                    layer.msg(result.msg);

                    if (result.code != 200)
                    {
                        return false;
                    }

                    $("#page").val(1);

                    //渲染聊天记录
                    getChatLog(result.data.list,user_id);
                },
                error : function() {
                    $("#sendBut").attr('disabled',false);
                    layer.msg('服务器连接失败');
                }
            });
        }
    }

    //检测滚动条是否到达顶部
    $(document).ready(function (){

        var nScrollTop  = 0;   //滚动到的当前位置

        var request_url = "<?php echo base_url(); ?>"+'index/getPageChatRecord';

        $("#chat-history").scroll(function(){
            var page    = $("#page").val();

            nScrollTop = $(this)[0].scrollTop;

            if(nScrollTop == 0)
            {
                var now_uid = $("#user_id").val();

                var to_uid  = $("#to_uid").val();

                var user_id     = $("#user_id").val();

                //获取上一页
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: request_url,
                    data: {
                        page: page,
                        to_uid:to_uid,
                        user_id:user_id,
                    },
                    success: function (result) {
                        layer.msg(result.msg);
                        if (result.code != 200)
                        {
                            return;
                        }

                        $("#page").val(parseInt(page) + parseInt("1"));

                        let arrNew = new Array();

                        var list = result.data.list;

                        for (var i = list.length - 1; i >= 0; i--) {

                            console.log(list[i].uid);
                            var log = '';
                            if (list[i].uid == now_uid)
                            {
                                log = '<li class="clearfix">' +
                                    '<div class="message-data align-right"><span class="message-data-time" >'+list[i].create_time+'</span> &nbsp; &nbsp;<span class="message-data-name" >'+list[i].nick_name+'</span> <img style="width: 40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" /></div>' +
                                    '<div class="message other-message float-right">'+list[i].content+'</div>'+
                                    '</li>';
                            } else {
                                log = '<li>' +
                                    '<div class="message-data"><span class="message-data-name"><img style="width: 40px;margin-bottom: -13px;" src="'+list[i].url+'" alt="avatar" />'+list[i].nick_name+'</span> <span class="message-data-time" >'+list[i].create_time+'</span></div>' +
                                    '<div class="message my-message">'+list[i].content+'</div>'+
                                    '</li>';
                            }

                            arrNew.push(log);
                        }

                        var old = $("#chat_box").html();

                        var newLog = arrNew + old;

                        $("#chat_box").html(newLog);
                    },
                    error : function() {
                        layer.msg('服务器连接失败');
                    }
                });
            }

        });
    });

    //表情
    function test()
    {
        layer.msg('开发中');
    }

    //回车提交
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            $("#sendMsg").trigger("click");
        }
    });

    //头像投稿
    function avatarUpload()
    {
        layer.open({
            title:"欢迎投稿头像，接受任何风格",
            content: ' <input style="width: 215px;height: 33px;" onchange="uploadDesc(this.value)" type="file" accept="image/gif,image/jpeg,image/jpg,image/png" multiple="multiple" id="img_up" class="layui-input">' +
                '<div id="FileArea" style="color: black"></div>',
            btn: ['上传','取消'],
            btn1: function(index){
                //按钮【按钮一】的回调
                var request_url = "<?php echo base_url(); ?>"+'index/uploadAvatar';

                var uid = $('#user_id').val();

                var formData = new FormData();
                formData.append('image', $('#img_up')[0].files[0]);
                formData.append('uid', uid);
                console.log(formData)

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    cache: false,
                    processData: false,
                    contentType: false,
                    url: request_url,
                    data: formData,
                    success: function (result) {
                        layer.msg(result.msg);
                        if (result.code != 200)
                        {
                            return false;
                        }

                        layer.close(index);//关闭弹框
                    },
                    error : function() {
                        layer.msg('服务器连接失败');
                    }
                });
            },
        });
    }

    function uploadDesc(val)
    {
        $("#FileArea").text(val);
    }

</script>

<script>
    //表情
    $.emoticons({
        'activeCls':'trigger-active'
    },function(api){
        var $content = $('textarea[name="message-to-send"]');
        var $result  = $('#result');
        $('#format').click(function(){
            $result.html(api.format($content.val()));
        });
    });
</script>

</html>